package com.card.server.service.impl;

import com.card.server.config.RedisService;
import com.card.server.domain.Player;
import com.card.server.domain.R;
import com.card.server.domain.Room;
import com.card.server.domain.RoomEmitters;
import com.card.server.enums.TimeEnum;
import com.card.server.service.IRoomService;
import com.card.server.utils.JsonUtils;
import com.card.server.utils.RoomUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import reactor.core.publisher.FluxSink;

/**
 * @author TISNIW
 * @version 1.0
 * @date 2025/5/26 16:49
 * @desc
 */
@Service
public class RoomServiceImpl implements IRoomService {
    private static final Logger log = LoggerFactory.getLogger(RoomServiceImpl.class);
    @Autowired
    private RoomUtil roomUtil;
    @Autowired
    private RedisService redisService;
    @Override
    public R<String> enter(Integer userId, String roomKey) {
        // 1. 从 Redis 获取房间信息
        Room room = redisService.getCacheObject(roomKey, Room.class);

        if (room == null) {
            return R.fail(3001,"房间不存在");
        }
        // 2. 查找用户并更新状态
        boolean found = false;
        for (Player player : room.getPlayers()) {
            if (player.getId().equals(userId)) {
                player.setStatus(1); // 设置为已准备
                found = true;
                break;
            }
        }

        if (!found) {
            return R.fail(3001,"用户不在房间内");
        }
        // 3. 保存回 Redis
        redisService.setCacheObject(roomKey, JsonUtils.writeValueAsString(room), TimeEnum.ONE_DAY);

        return R.ok("进入房间成功");
    }
    @Scheduled(fixedRate = 1000)
    public void checkRoom() {
        roomUtil.checkRoom();

    }
}
